const jsonwebtoken = require('jsonwebtoken');
const UserModule = require('../modules/user')
const config = require('../config/default')
const BaseController = require('./base')

module.exports = class UserController extends BaseController {
  async login(ctx) {
    let { name, password } = ctx.request.body
    let user = await UserModule.findOne({ name, password })
    if (!user) {
      this.error(ctx, '用户名密码不匹配', 400)
    }

    let token = jsonwebtoken.sign(
      { name: user.name, id: user.id },  // 加密userToken
      config.SECRET,
      { expiresIn: process.env['jwt.timeout'] }
    )
    ctx.cookies.set(process.env['token.name'], token, {
      domain: 'sunxq.top',
      httpOnly: false,
    })

    this.success(ctx, '登录成功')
  }

  async get(ctx) {
    ctx.body = await UserModule.findOne(ctx.request.body.id)
  }

  async delete(ctx) {
    ctx.body = await UserModule.del(ctx.request.body.id)
  }

  async list(ctx) {
    ctx.body = await UserModule.findAll()
  }

  async create(ctx) {
    const {
      name, password
    } = ctx.request.body
    await UserModule.add({
      name, password
    })
    ctx.body = {
      return: true
    }
  }

}